package com.frame.library.db;

import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import java.io.File;

/**
 * Added by Tom on 2024/06/28.
 * 单例, 工厂
 */
public class DaoSupportFactory {
    private static DaoSupportFactory mFactory;
    // 持有外部数据库的引用
    private SQLiteDatabase mSqliteDatabase;

    private DaoSupportFactory() {
        // 判断是否有存储卡读写权限，6.0要动态申请权限。
        File dbRoot = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "nhdz" // 内涵段子
                + File.separator + "database");
        if (!dbRoot.exists()) {
            dbRoot.mkdirs();
        }
        File dbFile = new File(dbRoot, "nhdz.db"); // 内涵段子
        // 打开或创建数据库，把数据库放到手机的内存卡里面。
        mSqliteDatabase = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    }

    public static DaoSupportFactory getFactory() {
        if (mFactory == null) {
            synchronized (DaoSupportFactory.class) {
                if (mFactory == null) {
                    mFactory = new DaoSupportFactory();
                }
            }
        }
        return mFactory;
    }

    // 拿到接口，通过接口插入数据
    public <T> IDaoSupport getDao(Class<T> clazz) {
        IDaoSupport daoSupport = new DaoSupport(); // TODO 可更换其他方案，具体的实现类。
        daoSupport.init(mSqliteDatabase, clazz); // 初始化数据库

        return daoSupport;
    }

}
